import axios, { AxiosInstance, AxiosPromise } from 'axios';

interface ResponseInstance {
    code: string;
    data: any;
    message: string;
}

type getRequestFunc = (
    url: string,
    params: object
) => AxiosPromise<ResponseInstance>;

type postRequestFn = (
    url: string,
    data: object
) => AxiosPromise<ResponseInstance>;

class Http {
    /**
     * axios 实例
     */
    private axios: AxiosInstance;

    /**
     * 构造函数
     */
    constructor() {
        this.axios = axios.create();
        this.axios.defaults.timeout = 10000;
        // 配置请求拦截器
        this.useRequestInterceptor();
        // 配置响应拦截器
        this.useResponseInterceptor();
    }

    /**
     * 拦截器配置
     */
    useRequestInterceptor() {
        this.axios.interceptors.request.use(config => {
            const token = window.sessionStorage.getItem('token');
            if (token) {
                config.headers.Authorization = token;
            }
            return config;
        });
    }

    /**
     * 拦截器配置
     */
    useResponseInterceptor() {
        this.axios.interceptors.response.use(response => {
            return response;
        });
    }

    /**
     * GET 请求
     */
    public get: getRequestFunc = (url, params = {}) =>
        this.axios.get(url, { params });

    /**
     * POST 请求
     * @param url
     * @param data
     */
    public post: postRequestFn = (url, data = {}) => this.axios.post(url, data);
}

export default new Http();
